
import '../com.js'
import {  getDB } from "../indexedDB.js"
const db = getDB("MyDatabase", 2, [
  { name: "books", options: { keyPath: "id" }, indexes: [{ name: "chapters", keyPath: "chapters" }] },
  { name: "bookOnLineSetting", options: { keyPath: "id" } }
])

// const db = new IndexedDBWrapper("MyDatabase", 1, "books");
// const dbBookOnLineSetting= new IndexedDBWrapper("MyDatabase", 1, "bookOnLineSetting");
let book = {
  name: '',
  chapters: [],
  read: 0,
}
document.addEventListener("DOMContentLoaded", () => {
  console.log("DOM 已加载完成！", domKey);
  // 在此执行你的逻辑（如修改页面内容）
  init()
});






document.getElementById('modifyBtn').addEventListener('click', () => {
  changeContent('aaaa', domKey)
});
document.getElementById('initBtn').addEventListener('click', () => {
  init()
});

document.getElementById('saveBtn').addEventListener('click', async () => {
  // 获取当前标签页

  const chapter = document.getElementById('chapter').value;
  if (book.chapters.length < 1) {
    console.log('未找到数据', book)
    return
  }
  book.read = chapter * 1
  turnPage()
  console.log('读取章节:book', book);
});




document.getElementById('modeSelect').addEventListener('change', (e) => {
  onChangeModel(e.target.value)
});
const init = async () => {
  // await Promise.all([db.initDB(), dbBookOnLineSetting.initDB()]);
  await db.initDB()

  const allBooks =await db.getAll("books")
  const bookOnLineSetting=await db.getAll("bookOnLineSetting")
  console.log('bookOnLineSetting', bookOnLineSetting,allBooks)
  if (allBooks.length < 1) {
    console.log('未找到数据', allBooks)
    return
  }
  console.log('allBooks', allBooks)
  book = allBooks[0]
  if (book) {
    document.getElementById('chapter').value = book.read
    const content = book.chapters[book.read]
    console.log('content', content)
    showContent(`${content.title}        
        ${content.detail}
        `)
    //给下拉数据填充数据
    const selectElement = document.getElementById('bookSelect');
    allBooks.forEach(item => {
      const option = document.createElement('option');
      option.value = item.id;
      option.textContent = item.id;
      selectElement.appendChild(option);
    });
  }

}

const onChangeModel=(value)=>{
  if(value=='1'){
    document.getElementById('bookModel-1').style.display = 'block' 
    document.getElementById('bookModel-2').style.display = 'none'
  }else{
    document.getElementById('bookModel-1').style.display = 'none' 
    document.getElementById('bookModel-2').style.display = 'block'
  }
}
/**
 * 监控后台转发的动作
 */
chrome.runtime.onMessage.addListener(async (message) => {
  console.log('按下按键了')
  if (message.action === "left-arrow-pressed") {
    console.log("用户按下了左箭头键");
    // 在此执行左箭头操作
    book.read--;
    turnPage()

  } else if (message.action === "right-arrow-pressed") {
    console.log("用户按下了右边箭头键");
    // 在此执行左箭头操作
    book.read++
    turnPage()
  }
});

const turnPage = async () => {
  const content = book.chapters[book.read]
  if (!content) return console.log("获取章节失败 --turnPage");
  showContent(`${content.title}        
    ${content.detail}
    `)

  await saveChapter(book.read)
  changeContent(`${content.title}      
    ${content.detail}`, domKey)
}
/**
 * 保存章节
 * @param {*} newChapter 
 */
const saveChapter = async (newChapter) => {
  book.read = newChapter
  document.getElementById('chapter').value = newChapter
  await db.update('books',{ id: book.id, chapters: book.chapters, read: newChapter * 1 });

}

const showContent = async (text) => {
  const dom = document.getElementById('content')
  dom.innerHTML = text
}
// 在用户交互（如按钮点击）后调用
document.getElementById('fileInput').addEventListener('change', (e) => {
  const file = e.target.files[0];
  if (!file) return;


  const reader = new FileReader();
  reader.onload = async (event) => {
    try {
      // 1. 读取文件内容
      const text = event.target.result;

      // 2. 分章节处理
      const chapters = splitNovelChapters(text);
      console.log('chapters', chapters)

      if (chapters.length < 1) {
        readerGBK(file)
      } else {
        onSaveBook(file, chapters)
      }


    } catch (error) {
      console.error('导入失败:', error);
      showStatus(`错误: ${error.message}`, 'error');
    }
  };
  if (typeof reader.readAsText === 'function' &&
    reader.readAsText.length === 2) { // 检查是否支持编码参数
    reader.readAsText(file, 'GBK');
  } else {
    reader.readAsText(file); // 回退默认UTF-8
  }
  // reader.readAsText(file, 'UTF-8');
});

const readerGBK = async (file) => {
  const reader = new FileReader();
  reader.onload = async (event) => {
    try {
      // 1. 读取文件内容
      const text = event.target.result;

      // 2. 分章节处理
      const chapters = splitNovelChapters(text);
      console.log('chapters', chapters)

      if (chapters.length < 1) {

        showStatus(`错误: 未找到有效数据`, 'error');
      } else {
        onSaveBook(file, chapters)
      }


    } catch (error) {
      console.error('导入失败:', error);
      showStatus(`错误: ${error.message}`, 'error');
    }
  };
  reader.readAsText(file, 'GBK');
}
const onSaveBook = async (file, chapters) => {
  // 3. 生成唯一存储键名
  const bookKey = file.name.replace(/.txt$/i, '');
  // 打开数据库
  const allBooks = await db.query();
  console.log("所有书籍:", allBooks);
  await db.add('books',{ id: bookKey, chapters: chapters, read: 0 });
  showStatus('导入成功！', 'success');
}

const divideTheChapter = (content) => {
  const regexp = /(?<=\r\n)(\s*)([第序]{1}.*?[章幕卷篇]{1}.*?)(?=\r\n)/g;
  let list = content.replace(regexp, function ($1) {
    return "@@@" + $1.trim() + "___";
  }).split("@@@").filter(item => item);

  console.log('list', list)
  if (list.length < 2) {
    console.log('未找到章节')
    const regexp2 = /(^|\n)\s*([第序][^第序章幕卷篇\n]*[章幕卷篇][^\n]*)/g;
    list = content.replace(regexp2, "@@@$2___").split("@@@").filter(Boolean);

  }

  list = list.map(item => {
    let str = item.split("___")[1] ? item.split("___")[0] + " " + item.split("___")[1] : null;
    str = str ? str.trim() : "";
    if (str) {
      const index = str.indexOf("\n");
      const title = str.substring(0, index).trim();
      const detail = str.substring(index + 1).trim();
      if (title && detail) {
        return {
          title: title,
          detail: detail
        };
      }
      else {
        return null;
      }
    }
    return null;
  }).filter(item => item);
  return list;


}
// 章节分割函数
function splitNovelChapters(text) {

  let novelsArray = divideTheChapter(text);


  return novelsArray

}

// 状态显示函数
function showStatus(message, type = 'info') {
  const statusDiv = document.getElementById('status');
  statusDiv.textContent = message;
  statusDiv.className = `status-${type}`;
}